import ImageWall from "@/components/datasets/imageWall";
import { DataRecord } from "@prisma/client";
import { Button, Modal, Upload, UploadFile } from "antd";
import styles from "@/styles/Datasets.module.css";
import { useEffect, useState } from "react";
import { UploadChangeParam } from "antd/es/upload/interface";
import { UploadOutlined } from "@ant-design/icons";

type Props = {
  records: DataRecord[];
};
export default function Datasets() {
  const [records, setRecords] = useState<DataRecord[]>([]);
  useEffect(() => {
    fetch("http://localhost:3000/api/dataRecord")
      .then((res) => res.json())
      .then((data) => {
        setRecords(data);
      });
  }, []);
  // 导入数据对话框
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    fileList.forEach((uploadFile) => {
      const formData = new FormData();
      formData.append("image", uploadFile.originFileObj as File);
      formData.append("name", uploadFile.name);
      fetch("api/dataRecord", { method: "POST", body: formData });
    });
    setIsModalOpen(false);
    setFileList([]);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setFileList([]);
  };

  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const onFileChange = ({ file, fileList }: UploadChangeParam) => {
    if (file.status !== "uploading") {
      setFileList(fileList);
    }
  };
  return (
    <>
      <div className={styles.toolBar}>
        <Button type="primary" onClick={showModal}>
          导入数据
        </Button>
        <Modal
          title="上传图片"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Upload onChange={onFileChange} multiple>
            <Button icon={<UploadOutlined />}>Click to Upload</Button>
          </Upload>
        </Modal>
      </div>
      <ImageWall records={records}></ImageWall>
    </>
  );
}
